import { useState, useEffect } from 'react'
import { Button, Menu } from 'antd'
import { MenuUnfoldOutlined, MenuFoldOutlined, HomeOutlined, ClusterOutlined, UserOutlined } from '@ant-design/icons'
import { withRouter } from 'react-router-dom'

// 根据地址获取对应的KEY
const queryKey = (pathname) => {
    let [key] = pathname.match(/\/[^/]+/) || ['/home']
    return key
}

const CommonMenu = function CommonMenu({ history, location }) {
    // 左侧Menu的数据
    const menuItem = [{
        key: '/home',
        label: '控制面板',
        icon: <HomeOutlined />
    }, {
        key: '/category',
        label: '分类管理',
        icon: <ClusterOutlined />
    }, {
        key: '/personal',
        label: '个人中心',
        icon: <UserOutlined />
    }]

    // 定义状态
    let [collapsed, setCollapsed] = useState(false),
        [keys, setKeys] = useState(() => {
            // 组件第一次渲染：控制默认选中谁
            return [queryKey(location.pathname)]
        })

    // 点击Menu的每一项
    const menuClick = ({ key }) => {
        // key存储的是每一项的key值（也就是要跳转的路由地址）
        let curKey = queryKey(location.pathname)
        if (key === curKey) return
        history.push(key)
        // 每一次点击MenuItem跳转完毕，把最新的KEY设置好
        setKeys([key])
    }

    useEffect(() => {
        let unlisten = history.listen(() => {
            // 监测到路由的变化：按照最新的地址设置选中的KEY
            let key = queryKey(window.location.hash)
            setKeys([key])
        })
        return () => {
            if (unlisten) unlisten()
        }
    }, [])

    return <div className="menu-box">
        <Button type="primary"
            onClick={() => {
                setCollapsed(!collapsed)
            }}>
            {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
        </Button>
        <Menu mode="inline" theme="dark"
            items={menuItem}
            selectedKeys={keys}
            inlineCollapsed={collapsed}
            onClick={menuClick} />
    </div>
}
export default withRouter(CommonMenu)